package org.goodsl.mdd;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Hashtable;

/**
 * Created with IntelliJ IDEA.
 * User: 萧猛
 * Date: 12-10-29
 * Time: 下午4:57
 * To change this template use File | Settings | File Templates.
 */
public class BoxBuilder {

    /**
     * 缓存类型解析后获取的字段信息，避免重复解析
     */
    private static Hashtable<String, BoxInfo> cachedBoxInfo =
        new Hashtable<String, BoxInfo>();

    private static HashMap<Class,Object> defaultValues  =
            new HashMap<Class, Object>(18);


    //各种数据类型的默认初始值
    static {
        defaultValues.put(boolean.class,Boolean.FALSE);
        defaultValues.put(byte.class,new Byte((byte)0));
        defaultValues.put(char.class,"");
        defaultValues.put(short .class,new Short((short)0));
        defaultValues.put(int .class,new  Integer(0));
        defaultValues.put(long .class,new Long((long)0));
        defaultValues.put(float .class,new Float((float)0));
        defaultValues.put(double .class,new Double((double)0));

        defaultValues.put(Integer.class, new  Integer(0));
        defaultValues.put(Byte.class, new Byte((byte)0));
        defaultValues.put(Character.class, "");
        defaultValues.put(Short.class, new Short((short)0));
        defaultValues.put(Boolean.class, Boolean.FALSE);
        defaultValues.put(Long.class, new Long((long)0));
        defaultValues.put(Float.class,  new Float((float)0));
        defaultValues.put(Double.class, new Double((double)0));
        defaultValues.put(BigDecimal.class, new BigDecimal(0));
        defaultValues.put(BigInteger.class, BigInteger.valueOf(0));


    }

    public static Box makeBox(Class<?> cz)throws Exception{
       return makeBox(cz,false);
    }

     /**
     * 构造指定类型的对象实例
     * @param cz
     * @return
     */
    public static Box makeBox(Class<?> cz,boolean forParse)throws Exception{

        BoxInfo boxInfo = getBoxInfo(cz);
        if(boxInfo!=null)
            return boxInfo.create(forParse);
        return null;
    }
    public static BoxInfo getBoxInfo(Class<?> cz) throws Exception{
        //先从缓存中获取字段信息
        BoxInfo boxInfo = cachedBoxInfo.get(cz.getName());
        if(boxInfo == null){
            if(!Box.class.isAssignableFrom(cz))
                throw new Exception(cz.getName()+ " 必须继承自 " + Box.class.getName());
            boxInfo = new BoxInfo(cz);
            cachedBoxInfo.put(cz.getName(),boxInfo);
        }
        return  boxInfo;

    }
    public static Object getTypeDefaultValue(Class cz)throws ParseException{

        if(defaultValues.containsKey(cz))
            return defaultValues.get(cz);

        try {
            return cz.newInstance();

        } catch(Exception e ){
            throw new ParseException("类型" +  cz.getName() + " 必须有一个无参数的构造函数",e);

        }
    }


}

